import PDFViewer from "./PDFViewer"
import PDFFindbar from "./PDFFindbar"
import { getDocument, GlobalWorkerOptions } from "pdfjs-dist/lib/pdf";
import PdfjsWorker from "pdfjs-dist/lib/pdf.worker";

export { PDFViewer,PDFFindbar,getDocument,GlobalWorkerOptions }

function PDFPool (){
    let _viewers = []
       ,_pdfdoc
    
    function setPdfWorker(workerSrcOrClass) {
        if (typeof window !== "undefined") delete window.pdfjsWorker;
        delete GlobalWorkerOptions.workerSrc;
        delete GlobalWorkerOptions.workerPort;

        if (typeof workerSrcOrClass === "string") {
            GlobalWorkerOptions.workerSrc = workerSrcOrClass;
        } else if (typeof workerSrcOrClass === "function") {
            GlobalWorkerOptions.workerPort = workerSrcOrClass();
        } else if (workerSrcOrClass instanceof Worker) {
            GlobalWorkerOptions.workerPort = workerSrcOrClass;
        } else if (typeof window !== "undefined" && workerSrcOrClass) {
            window.pdfjsWorker = workerSrcOrClass;
        }
    }

    const context = {
        getDocument,
        setPdfWorker,
        addViewer(val){
            _viewers.push(val)
        },
        removeViewer(val){
            _viewers.splice(_viewers.indexOf(val), 1)
        }
    }

    Object.defineProperties(context, {
        viewers: {
            get(){ return _viewers },
        },
        pdfdoc: {
            get(){ return _pdfdoc },
            set(val){ _pdfdoc = val }
        }
    })

    return Object.freeze(context)
}

const pdfPool = new PDFPool()
export default {
    install(Vue, options={}){
        if(typeof options.worker !== 'undefined'){
            pdfPool.setPdfWorker(options.worker)
        }else {
            pdfPool.setPdfWorker(PdfjsWorker)
        }
        Vue.prototype.$getPDFPool = ()=>pdfPool
        Vue.component('PDFViewer', PDFViewer)
        Vue.component('PDFFindbar', PDFFindbar)
    }
}